﻿using Digitalmes.Application.ThirdParty.Weber;
using Digitalmes.Domain;
using Digitalmes.Domain.Mes;
using Digitalmes.Scada.Events;
using Digitalmes.Sugar;
using MediatR;

namespace Digitalmes.ApiService.EventHandlers;

public class AfterArchivedHandler : INotificationHandler<AfterArchivedEvent>
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger _logger;

    public AfterArchivedHandler(IServiceProvider serviceProvider , ILogger<AfterArchivedHandler> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }

    public async Task Handle(AfterArchivedEvent notification, CancellationToken cancellationToken)
    {
        if (notification.State != (int)ErrCode.E0010)
        {
            return;
        }

        if (notification.Target is ProdTransSn transSn)
        {
            await ArchiveWeberFds(transSn);
        }
    }

    /// <summary>
    /// Weber FDS 归档
    /// </summary>
    /// <param name="transSn"></param>
    /// <returns></returns>
    private async Task ArchiveWeberFds(ProdTransSn transSn)
    {
        using var scope = _serviceProvider.CreateScope();

        try
        {
            // 检查当前是否为 FDS 工序
            var processRepo = scope.ServiceProvider.GetRequiredService<SugarRepository<ProcProcess>>();
            var process = await processRepo.GetByIdAsync(transSn.CurProcId);
            if (process?.ProcTypeCode == "FDS")
            {
                var weberService = scope.ServiceProvider.GetRequiredService<FdsWeberService>();
                await weberService.Archive(new FdsWeberArchiveInput { SN = transSn.Sn });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Weber FDS 数据存档失败，SN: {SN}，工位：{OpCode}", transSn.Sn, transSn.CurOpCode);
        }
    }
}
